/*
 * @Description: 组件事件
 * @Author: zhangwei
 * @Date: 2023-02-09 16:49:57
 * @LastEditTime: 2023-02-17 23:17:03
 * @LastEditors: zw 775925302@qq.com
 */

import type { CmpProtocal, EventObj } from "../../types/CmpProtocal";
import Bus from "@/config/mitt";

type EventProps = {
  [propName: string]: Function;
};

export class CmpEvent {
  eventProps: EventProps = {};

  private constructor(private mdata: CmpProtocal) {}

  static of(mdata: any) {
    return new CmpEvent(mdata);
  }

  parseEvent() {
    const firstLetterUpperCase = (str: string) => {
      const newStr: string = str.slice(0, 1).toUpperCase() + str.slice(1);
      return newStr;
    };

    this.mdata.events.forEach((v: EventObj) => {
      let eventName: string = firstLetterUpperCase(v.name);
      if (v.subfix == "Stop") {
        eventName = "on" + eventName + "v.subfix";
      } else if (v.subfix == "Capture") {
        eventName = "on" + eventName + "v.Capture";
      } else {
        eventName = "on" + eventName;
      }
      this.eventProps[eventName] = () => {
        Bus.emit("cmpEvent", {
          cmpData: this.mdata,
          callFnName: v.callFn,
        });
      };
    });
  }
}
